import 'dart:async';
import 'dart:math';

// import 'package:aliplayer_widget/utils/snack_bar_util.dart';
import 'package:aliplayer_widget/utils/snack_bar_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/subject/chapter_model.dart';
import 'package:hktk_app/pages/question/chapter_question_page.dart';
import 'package:hktk_app/provider/chapter_state.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:provider/provider.dart';

//递归显示章节做题组件
// 需要传入章节信息，一般跨层级注入必要信息(columnId,  categoryId)，但这里可以从缓存中拿取
class ChapterTree extends StatefulWidget {
  final ChapterModel chapter;
  final StreamController controller;
  final bool free;

  ChapterTree({
    super.key,
    required this.controller,
    required this.chapter,
    required this.free,
  });

  @override
  State<StatefulWidget> createState() => _ChapterTreeState();
}

class _ChapterTreeState extends State<ChapterTree> {
  late ChapterModel _chapter;
  late bool _loading=false;
  late BuildContext _context;

  @override
  void initState() {
    //   initState
    super.initState();
    _chapter = widget.chapter;
    //   首层是普通组件
    //   后面嵌套层级显示的展开组件
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // String? s=context.read<String?>();
    });
  }

  @override
  void dispose() {
    //   dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var provide = context.read<Map<String, dynamic>>();
    final state = context.watch<ChapterState>();
    var categoryId = state.categoryId??0;
    _context = context;

    // 
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 非叶子节点
          if (!_chapter.leaf!)
            GestureDetector(
              onTap: () {
                eventBus.fire(_chapter);
                if (_chapter.treeChildren == null) {
                  // 开启加载动画
                  setState(() {
                    _loading=true;
                  });
                  SubjectDao.childChapter(
                          columnId:
                          _context.read<Map<String, dynamic>>()["columnId"],
                          pId: _chapter.id!)
                      .then((res) {
                    SubjectDao.chapterRecordsIds(
                        industryCode: IndustryDao.getExamKey().industryId,
                        chapterIds: res.map((e) => e.id!).toList(),
                        examId:IndustryDao.getExamKey().examId,
                        // categoryId: state.categoryId!
                      categoryId: categoryId
                    ).then((response){
                      for(var i=0;i<res.length;i++){
                        res[i].ztNum=response[res[i].id]["dc"];
                      }
                      if (mounted) {
                        // 结束加载动画
                        _chapter.treeStatus = !_chapter.treeStatus;
                        _chapter.treeChildren = res;
                        _loading=false;
                        widget.controller.add(true);
                      }
                    });
                    // if (mounted) {
                    //   // 结束加载动画
                    //   _chapter.treeStatus = !_chapter.treeStatus;
                    //   _chapter.treeChildren = res;
                    //   _loading=false;
                    //   widget.controller.add(true);
                    // }
                  }).catchError((error){
                    if (mounted) {
                      // 显示错误信息
                      SnackBarUtil.error(context, "未知错误");
                      setState(() {
                        _loading=false;
                      });
                    }
                  });
                } else {
                  _chapter.treeStatus = !_chapter.treeStatus;
                  widget.controller.add(true);
                }
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      if (_chapter.treeStatus &&
                          _chapter.level == provide["topLevel"])
                        Transform.rotate(
                          angle: pi,
                          child: SvgPicture.asset(
                            "images/question/icon1_1.svg",
                            width: 16,
                            height: 16,
                          ),
                        )
                      else if (_chapter.treeStatus &&
                          _chapter.level != provide["topLevel"])
                        SvgPicture.asset(
                          "images/question/icon1_2.svg",
                          width: 16,
                          height: 16,
                        )
                      else if (!_chapter.treeStatus &&
                          _chapter.level == provide["topLevel"])
                        SvgPicture.asset(
                          "images/question/icon1_1.svg",
                          width: 16,
                          height: 16,
                        )
                      else
                        Transform.rotate(
                          angle: pi,
                          child: SvgPicture.asset(
                            "images/question/icon1_2.svg",
                            width: 16,
                            height: 16,
                          ),
                        ),
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                          child: Text(
                        _chapter.name!,
                        style: _chapter.level == provide["topLevel"]
                            ? TextStyle(
                                fontSize: 18, fontWeight: FontWeight.w500)
                            : TextStyle(fontSize: 14),
                      ))
                    ],
                  ),
                  Row(
                    children: [
                      SizedBox(
                        height: 10,
                        width: 100,
                        child: LinearProgressIndicator(
                          value: _chapter.qcount! > 0
                              ? (_chapter.ztNum ?? 0) / _chapter.qcount!
                              : 0,
                          backgroundColor: colorWhite2,
                          valueColor: const AlwaysStoppedAnimation(colorBlue1),
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                      SizedBox(
                        width: 8,
                      ),
                      Text.rich(
                        TextSpan(
                          children: [
                            TextSpan(
                                text: _chapter.ztNum.toString(),
                                style: _chapter.ztNum! > 0
                                    ? FontUtil.fontBlue1(12)
                                    : FontUtil.fontGrey2(12)),
                            TextSpan(
                                text: "/${_chapter.qcount}道",
                                style: FontUtil.fontGrey2(12)),
                          ],
                        ),
                      )
                    ],
                  )
                ],
              ),
            )
          else
            Container(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(child: Text(_chapter.name!)),
                    if (widget.free)
                      GestureDetector(
                          onTap: () {
                            eventBus.fire(_chapter);
                            var columnId = context
                                .read<Map<String, dynamic>>()["columnId"];
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ChapterQuestionPage(
                                  id: _chapter.id!,
                                  collType: CollectionTypeEnum.chapter,
                                  columnId: columnId,
                                  cId: _chapter.id!,
                                  rType: CtEnum.chapter,
                                ),
                                settings: const RouteSettings(
                                    name: "ChapterQuestionPage"),
                              ),
                            );
                          },
                          // style: TextButton.styleFrom(
                          //   padding: EdgeInsets.only(
                          //       left: 20, right: 20),
                          //   // shape: RoundedRectangleBorder(
                          //   //   borderRadius: BorderRadius.circular(30.0),
                          //   // ),
                          //   side:
                          //       BorderSide(color: Color(0xFF3C6CFF), width: 1),
                          // ),
                          child: Text(
                            "做题",
                            style: TextStyle(
                                fontSize: 16, color: Color(0xFF3C6CFF)),
                          ))
                    else
                      TextButton(
                          onPressed: () {},
                          child: SvgPicture.asset(
                            "images/home/course_s.svg",
                            width: 28,
                            height: 28,
                          ))
                  ],
                ),
                Row(
                  children: [
                    SizedBox(
                      height: 10,
                      width: 100,
                      child: LinearProgressIndicator(
                        value: _chapter.qcount! > 0
                            ? (_chapter.ztNum ?? 0) / _chapter.qcount!
                            : 0,
                        backgroundColor: colorWhite2,
                        valueColor: const AlwaysStoppedAnimation(colorBlue1),
                        borderRadius: BorderRadius.circular(5),
                      ),
                    ),
                    SizedBox(
                      width: 8,
                    ),
                    Text.rich(
                      TextSpan(
                        children: [
                          TextSpan(
                              text: _chapter.ztNum.toString(),
                              style: _chapter.ztNum! > 0
                                  ? FontUtil.fontBlue1(12)
                                  : FontUtil.fontGrey2(12)),
                          TextSpan(
                              text: "/${_chapter.qcount}道",
                              style: FontUtil.fontGrey2(12)),
                        ],
                      ),
                    )
                  ],
                )
              ],
            )),
            if(_loading)
              Center(
                child: CircularProgressIndicator(),
              )
             ,
          // Container(
          //   padding: EdgeInsets.only(left: 16),
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: [
          //       // 如果有子节点
          //       if (!_chapter.leaf! && _chapter.treeChildren != null)
          //         for (var item in _chapter.treeChildren!) ...[
          //           ChapterTree(
          //             key: ValueKey(item.id),
          //             free: widget.free,
          //             controller: widget.controller,
          //             chapter: item,
          //           ),
          //           SizedBox(
          //             height: 16,
          //           )
          //         ]
          //       ,
          //     ],
          //   ),
          // )
            ClipRect(
                child: Align(
              child: Offstage(
                offstage: _chapter.treeStatus,
                child: TickerMode(
                  // enabled: _chapter.treeStatus,
                  enabled:true,
                  child: Container(
                    padding: EdgeInsets.only(left: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 如果有子节点
                        if (!_chapter.leaf! && _chapter.treeChildren != null)
                        for (var item in _chapter.treeChildren!) ...[
                          ChapterTree(
                            key: ValueKey(item.id),
                            free: widget.free,
                            controller: widget.controller,
                            chapter: item,
                          ),
                          SizedBox(
                            height: 16,
                          )
                        ]
                        ,
                      ],
                    ),
                  ),
                ),
              ),
            ))
        ],
      ),
    );
  }
}
